package cn.com.nes.site.config;

import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.naming.NamingFactory;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.Properties;

@Configuration
public class NacosConfig {

    @Value("${nacos.server-addr}")
    private String serverAddr;

    @Value("${service.name}")
    private String serviceName;

    @Value("${server.ip}")
    private String ip;

    @PostConstruct
    public void init() {
        try {
            // 配置 Nacos 客户端的连接信息
            Properties properties = new Properties();
            properties.put(PropertyKeyConst.SERVER_ADDR, serverAddr);
            properties.put(PropertyKeyConst.NAMESPACE, "public");

            // 创建 NamingService 实例
            NamingService namingService = NamingFactory.createNamingService(properties);

            // 创建一个 Instance 对象表示这个服务
            Instance instance = new Instance();
            instance.setIp(ip);
            instance.setPort(8080);
            instance.setServiceName(serviceName);

            // 将服务注册到 Nacos
            namingService.registerInstance(serviceName, instance);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
